﻿using Mysoft.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using 检查财务接口重合表调整.Model;

namespace 检查财务接口重合表调整
{
    public partial class Form1 : Form
    {
        private const string EntityPath = @"slxt_cwjkdy\src\00_根目录\_metadata\Entity";

        //解析需要对比的表
        private List<string> CompareTables = new List<string>();
        /// <summary>
        /// 获取原始tag代码
        /// </summary>
        List<MetadataEntity> AMetadatas = new List<MetadataEntity>();

        /// <summary>
        /// 获取对比的代码
        /// </summary>
        List<MetadataEntity> BMetadatas = new List<MetadataEntity>();


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.txtRestult.Text = " ";
            this.txtSqlBm.Text = " ";
            try
            {
                this.button1.Enabled = false;
                //1、解析需要对比的表
                GetCompareTables();
                //2、获取原始tag代码
                AMetadatas = GetGitAndMates(Const.原始tag, FeatureTypeEnum.Tag);
                //3、获取对比的代码
                BMetadatas = GetGitAndMates(this.txtNowFeature.Text.Trim(), FeatureTypeEnum.Feature);
                //4、进行比较
                var sbResult = new StringBuilder();
                foreach (var a in AMetadatas)
                {
                    var b1 = BMetadatas.FirstOrDefault(b => string.Equals(b.Name, a.Name, StringComparison.OrdinalIgnoreCase));
                    if (b1 == null)
                    {
                        throw new Exception("在最新分支中未找到表：" + a.Name);
                    }
                    if (b1.ToJson() != a.ToJson())
                    {
                        sbResult.Append(a.Name + "\r\n");
                    }
                }
                this.txtRestult.Text = sbResult.ToString();
                MessageBox.Show("检查成功！");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally {
                this.button1.Enabled = true;
            }
        }


        private List<MetadataEntity> GetGitAndMates(string featurea, FeatureTypeEnum featureTypeEnum)
        {

            GitHelper giteHelper = new GitHelper();
            //获取代码
            giteHelper.Clone(Const.GitUrl, featurea, featureTypeEnum);
            //获取元数据
            string path = giteHelper.GetRootPath();
            string entityPath = Path.Combine(path, EntityPath);
            var metadatas = GetMates(entityPath);

            if (featureTypeEnum == FeatureTypeEnum.Feature)
            {
                //解析升级sql编码
                CheckSqlBm(path);
            }
            //异步删除代码 
            new Task(() =>
            {
                Thread.Sleep(2000);
                PathHelper.DeletePath(path);
            }).Start();

            return metadatas;
        }

        private void CheckSqlBm(string path)
        {
            DirectoryInfo d = new DirectoryInfo(path);
            var sqlPath = Path.Combine(d.GetDirectories().First().FullName, "sql");
            List<string> errorSql = Xuh(sqlPath);
            if (errorSql.Count > 0)
            {
                this.txtSqlBm.Text = string.Join("\r\n", errorSql);
            }
        }
        private List<string> Xuh(string sqlPath)
        {
            List<string> list = new List<string>();
            DirectoryInfo d = new DirectoryInfo(sqlPath);
            foreach (var f in d.GetFiles())
            {
                if (string.Equals(f.Extension, ".sql", StringComparison.OrdinalIgnoreCase))
                {
                    var code = new FileCode().GetEncodingName(f);
                    if (string.Equals(code, "GB2312", StringComparison.OrdinalIgnoreCase) == false)
                    {
                        list.Add(f.Name);
                    }
                }
            }

            foreach (var directory in d.GetDirectories())
            {
                list.AddRange(Xuh(directory.FullName));
            }
            return list;
        }

        private List<MetadataEntity> GetMates(string path)
        {
            List<MetadataEntity> metadataEntityList = new List<MetadataEntity>();
            DirectoryInfo directoryInfo = new DirectoryInfo(path);
            FileStream fs;
            foreach (var f in directoryInfo.GetFiles())
            {
                XmlSerializer xs = new XmlSerializer(typeof(MetadataEntity));

                fs = f.OpenRead();
                MetadataEntity metadataEntity = (MetadataEntity)xs.Deserialize(fs);
                fs.Close();
                if (CompareTables.Contains(metadataEntity.Name))
                {
                    metadataEntityList.Add(metadataEntity);
                }
            }

            return metadataEntityList;
        }

        //解析需要对比的表
        private void GetCompareTables()
        {
            CompareTables = System.IO.File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory + Const.CompareTable), Encoding.Default).ToList();
        }
    }
}
